package com.itcv.mybatis.demo.dynamic.proxy;

import com.itcv.mybatis.demo.reflect.HelloMapper;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class DynamicProxy implements InvocationHandler {

    private HelloMapper helloMapper;

    public DynamicProxy(HelloMapper helloMapper){
        this.helloMapper = helloMapper;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        Object result = null;
        try{
            //调用目标方法
            //利用反射构造目标对象
            //    当代理对象调用真实对象的方法时，其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
            result=method.invoke(helloMapper,args);

        }catch(Exception e){
            System.out.println("ex:"+e.getMessage());
            throw e;
        }finally{
            System.out.println("after");
        }
        return result;
    }

    }

